<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用例管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="6">
          项目:
          <el-input
            v-model="queryInfo.epic"
            placeholder="请输入项目"
            @input="getTestcaseList()"
            clearable
            size="small"
          >
          </el-input>
        </el-col>
        <el-col :span="6">
          模块:
          <el-input
            v-model="queryInfo.feature"
            placeholder="请输入模块"
            @input="getTestcaseList()"
            clearable
            size="small"
          ></el-input>
        </el-col>
        <el-col :span="6">
          子模块:
          <el-input
            v-model="queryInfo.story"
            placeholder="请输入子模块"
            @input="getTestcaseList()"
            clearable
            size="small"
          ></el-input>
        </el-col>
        <el-col :span="6">
          测试标题:
          <el-input
            v-model="queryInfo.title"
            placeholder="请输入测试标题"
            @input="getTestcaseList()"
            clearable
            size="small"
          ></el-input>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 10px">
        <el-col :span="6">
          标签:
          <el-radio-group v-model="queryInfo.marks" @change="radioChange">
            <el-radio label="test"></el-radio>
            <el-radio label="pro"></el-radio>
            <el-radio label="core"></el-radio>
          </el-radio-group>
        </el-col>
        <el-col :span="6">
          状态:
          <el-select
            v-model="queryInfo.has_test_script"
            placeholder="请选择"
            size="small"
            clearable
            @change="selectChange"
          >
            <el-option
              v-for="item in status"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-row>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-row :gutter="60">
        <el-col :span="2">
          <el-button
            type="primary"
            size="mini"
            @click="uploadTestcaseDialogVisibal = true"
            >导入用例<i class="el-icon-upload el-icon--right"></i
          ></el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="success" size="mini"
            >导出用例<i class="el-icon-download el-icon--right"></i
          ></el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="warning" size="mini" @click="exportProject"
            >导出工程<i class="el-icon-s-promotion el-icon--right"></i
          ></el-button>
        </el-col>
      </el-row>
      <!-- 测试用例列表区域 -->
      <el-table
        :data="testcaseList"
        border
        stripe
        ref="multipleTable"
        @selection-change="handleSelectionChange"
        :row-key="getRowKeys"
      >
        <el-table-column
          label="#"
          type="selection"
          reserve-selection
        ></el-table-column>
        <el-table-column label="项目" prop="epic"></el-table-column>
        <el-table-column label="模块" prop="feature"></el-table-column>
        <el-table-column label="子模块" prop="story"></el-table-column>
        <el-table-column label="测试用例标题" prop="title"></el-table-column>
        <el-table-column
          label="测试用例编号"
          prop="test_case_id"
        ></el-table-column>
        <el-table-column label="测试页面" prop="page"></el-table-column>
        <el-table-column label="标签" prop="marks"></el-table-column>
        <el-table-column label="状态" prop="has_test_script">
          <template slot-scope="scope">
            {{ scope.row.has_test_script ? "已完成" : "未完成" }}
          </template>
        </el-table-column>
        <el-table-column label="测试人员" prop="tester"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 查看按钮 -->
            <!-- <el-tooltip
              effect="dark"
              content="查看"
              placement="top"
              :enterable="false"
            > -->
            <el-button type="text" size="mini" @click="viewTestCase(scope.row)"
              >查看</el-button
            >
            <!-- </el-tooltip> -->
            <!-- 删除按钮 -->
            <!-- <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            > -->
            <el-divider direction="vertical"></el-divider>
            <el-popconfirm
              title="确定执行该任务?"
              @confirm="deleteTestcase(scope.row.id)"
            >
              <el-button size="mini" type="text" slot="reference"
                >删除</el-button
              >
            </el-popconfirm>

            <!-- </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page_num"
        :page-sizes="[10, 20, 40, 80]"
        :page-size="queryInfo.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 查看测试用例对话框 -->
    <el-dialog
      title="用例详情"
      :visible.sync="viewTestCasedialogVisible"
      width="38%"
    >
      <!-- 内容主体区域 -->
      <div class="testcaseDialogTitle">用例名称：</div>
      <div class="testcaseDialogContent">{{ testcaseObj.title }}</div>
      <div class="testcaseDialogTitle">测试步骤：</div>
      <div class="testcaseDialogContent">{{ testcaseObj.steps }}</div>
      <div class="testcaseDialogTitle">期望结果：</div>
      <div class="testcaseDialogContent">{{ testcaseObj.expects }}</div>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="viewTestCasedialogVisible = false"
          type="primary"
          size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 上传测试用例对话框 -->
    <el-dialog
      title="导入用例"
      :visible.sync="uploadTestcaseDialogVisibal"
      width="30%"
      @close="cancelUploadTestcase"
    >
      <!-- 内容主体区域 -->
      <!-- action文件要上传到的api地址 -->
      <el-upload
        :action="uploadURL"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :on-error="handleError"
        :on-exceed="handleExceed"
        :before-upload="handleBeforeUpload"
        list-type="text"
        :auto-upload="false"
        ref="upload"
        accept=".xls,.xlsx"
        :limit="1"
        :file-list="fileList"
      >
        <el-button size="small" type="primary">选择文件</el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传xls/xlsx文件
        </div>
      </el-upload>
      <div style="color:#919191;font-size:13px; margin-top: 10px">
        <span>提示:</span><br />
        <span
          >1.文件导入前，请先下载导入模版：<el-link
            type="primary"
            href="http://10.51.40.30:5000/static/军民融合web自动化测试用例二期.xlsx"
            >用例模板</el-link
          ></span
        ><br />
        <span>2.请勿随意更改模板格式，并确保在导入时为最新模板</span><br />
        <span
          >3.最多导入100条，多次批量导入会覆盖之前的信息，按最新的导入数据为准</span
        >
      </div>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelUploadTestcase" size="small">取 消</el-button>
        <el-button type="primary" @click="uploadTestcase" size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        //  项目
        epic: "",
        // 模块
        feature: "",
        // 子模块
        story: "",
        // 测试标题
        title: "",
        // 用例编号
        test_case_id: "",
        // 是否存在测试脚本
        has_test_script: "",
        // 标记
        marks: "",
        // 当前的页数
        page_num: 1,
        // 当前每页显示多少条数据
        page_size: 10,
      },
      // 测试用例数据列表
      testcaseList: [],
      // 列表多选数据
      multipleSelection: [],
      // 用例总数
      total: 0,
      // 用例完成状态
      status: [
        {
          value: true,
          label: "已完成",
        },
        {
          value: false,
          label: "未完成",
        },
      ],
      //  控制查看用例详情对话框的显示与隐藏
      viewTestCasedialogVisible: false,
      testcaseObj: {},
      // 控制上传用例对话框的显示与隐藏
      uploadTestcaseDialogVisibal: false,
      // 上传用例的url地址
      uploadURL: "http://10.51.40.30:5000/testcase/upload",
      uploadURL: "http://10.51.40.30:5000/testcase/upload",
      // 上传文件列表数据
      fileList: [],
      getRowKeys(row) {
        // console.log(row)
        return row.id;
      },
    };
  },
  created() {
    // 查询测试用例
    this.getTestcaseList();
  },
  methods: {
    // 获取测试用例数据
    async getTestcaseList() {
      const { data: res } = await this.$http.post(
        "/testcase/list",
        this.qs.stringify(this.queryInfo)
      );
      // 查询失败
      if (res.code !== 200) {
        return this.$message.error("获取用例数据失败");
      }
      this.testcaseList = res.data;
      this.total = res.count;
    },

    // 监听 pageSize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.page_num = 1
      this.queryInfo.page_size = newSize;
      this.getTestcaseList();
    },

    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      // this.queryInfo.page_size = 10
      this.queryInfo.page_num = newPage;
      this.getTestcaseList();
    },

    // 监听标记值改变的事件
    radioChange(value) {
      console.log(value);
      this.getTestcaseList();
    },

    // 监听状态值改变的事件
    selectChange(value) {
      console.log(value);
      this.getTestcaseList();
    },

    // 删除测试用例
    async deleteTestcase(id) {
      //   console.log(confirmResult);
      const { data: res } = await this.$http.post(
        "/testcase/delete",
        this.qs.stringify({ id: id })
      );
      if (res.code != 200) {
        return this.$message.error(res.msg);
      }
      this.$message.success(res.msg);
      this.getTestcaseList();
    },
    viewTestCase(data) {
      this.testcaseObj = data;
      this.viewTestCasedialogVisible = true;
    },
    // 处理移除文件的操作
    handleRemove() {},

    // 处理上传成功时的操作
    handleSuccess(response, file, fileList) {
      if (response.code !== 200) {
        // console.log(1234567)
        console.log(file);
        console.log(fileList);
        this.$refs.upload.clearFiles();
        return this.$message.error(response.msg);
      }
      this.$message.success(response.msg);
      this.$refs.upload.clearFiles();
      this.uploadTestcaseDialogVisibal = false;
      this.getTestcaseList();
    },
    // 处理上传失败时的操作
    handleError(err, file, fileList) {
      // console.log(err);
      // console.log(file);
      // console.log(fileList);
    },

    // 处理上传文件超过限制
    handleExceed() {
      this.$message.error("每次最多只能上传一个文件");
    },

    // 上传文件前，文件校验
    handleBeforeUpload(file) {
      // this.fileList.push(file)
      // console.log(111111111111111111)
      // console.log(this.fileList)
      // if(!file){
      //   this.$message.error('请选择上传文件')
      // }
      // if(this.fileList.length === 0){
      //   this.$message.error('请选择上传文件')
      // }
    },

    // 取消上传文件
    cancelUploadTestcase() {
      this.$refs.upload.clearFiles();
      this.uploadTestcaseDialogVisibal = false;
    },

    // 上传用例文件
    uploadTestcase() {
      console.log(this.fileList);
      if (this.$refs.upload.uploadFiles.length === 0) {
        this.$message.error("请选择上传文件");
      }
      this.$refs.upload.submit();
    },

    // 监听多选列表数据变化
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(val);
    },

    // 导出工程
    exportProject() {
      if (this.multipleSelection.length == 0) {
        return this.$message.error("请至少勾选一条用例");
      }
      // this.$http.headers["Content-Type"] =
      //     "application/json;charset=UTF-8";
      this.$http
        .post("/testcase/export_project", this.multipleSelection, {
          headers: { "Content-Type": "application/json;charset=UTF-8" },
          responseType: "blob", //服务器返回的数据类型
        })
        .then(
          (res) => {
            console.log(res.headers);
            const content = res.data;
            const blob = new Blob([content]); //构造一个blob对象来处理数据
            const fileName = new Date().getTime() + ".zip";

            //对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
            //IE10以上支持blob但是依然不支持download
            if ("download" in document.createElement("a")) {
              //支持a标签download的浏览器
              const link = document.createElement("a"); //创建a标签
              link.download = fileName; //a标签添加属性
              link.style.display = "none";
              link.href = URL.createObjectURL(blob);
              document.body.appendChild(link);
              link.click(); //执行下载
              URL.revokeObjectURL(link.href); //释放url
              document.body.removeChild(link); //释放标签
            } else {
              //其他浏览器
              navigator.msSaveBlob(blob, fileName);
            }
          },
          (err) => {
            console.log(err);
          }
        );
    },
  },
};
</script>

<style lang="less" scoped>
.el-input {
  width: auto;
}

.el-radio {
  margin-right: 15px;
}

/deep/.el-radio__label {
  padding-left: 5px !important;
}

.testcaseDialogContent {
  white-space: pre-line;
  display: inline-block;
  margin-left: 30px;
  //   background-color: gray;
}

/deep/ .el-dialog__header {
  border-bottom: 1px solid #c1c1c1;
}

/deep/ .el-dialog__body {
  padding: 15px 20px;
  border-bottom: 1px solid #c1c1c1;
}

.testcaseDialogTitle {
  font-weight: bolder;
}
</style>
